{{ define "js" }}
  <script type="text/javascript" src="/js/datatables.min.js"></script>
  <script type="text/javascript" src="/js/datatable_input.js"></script>
  <script type="text/javascript" src="/js/datatable_loader.js"></script>

  <script>
    // live update for current block id
    {
      var ticker = document.getElementById("live-highest-block")
      var highestID = 0

      async function updateHighestBlock() {
        if (highestID != 0) {
          const response = await fetch(`${window.location.pathname}/highest`)
          if (response.ok && response.status == 200) {
            const text = await response.text()
            const diff = text - highestID
            if (diff > 0) {
              if (diff == 1) {
                ticker.innerHTML = "(" + diff + " new block found, reload page to show it)"
              } else {
                ticker.innerHTML = "(" + diff + " new blocks found, reload page to show them)"
              }
            }
          }
        }
      }

      setInterval(updateHighestBlock, 10000)
    }

    // data table
    $(document).ready(function () {
      $("#blocks").DataTable({
        searchDelay: 0,
        processing: true,
        serverSide: true,
        ordering: false,
        searching: false,
        ajax: dataTableLoader("/blocks/data", new URLSearchParams([["recordsTotal", highestID]])),
        pageLength: 10,
        pagingType: "input",
        language: {
          searchPlaceholder: "Block Number / Graffiti",
          search: "",
          paginate: {
            previous: "<",
            next: ">",
          },
        },
        columnDefs: [
          {
            targets: 4,
            data: "4",
            render: function (data, type, row) {
              return `<a class="text-monospace" href="address/${data}#blocksMined" data-toggle="tooltip" data-placement="top" title="0x${data}">0x${data.substr(0, 4)}...${data.substr(data.length - 4, data.length)}</a><i class="fa fa-copy text-muted p-1" role="button" data-toggle="tooltip" title="Copy to clipboard" data-clipboard-text="0x${data}"></i>`
            },
          },
        ],
        stateSave: true,
        stateSaveCallback: function (settings, data) {
          data.order = []
          fetch(`/tables/${settings.sTableId}/state`, {
            method: "PUT",
            body: JSON.stringify(data),
          })
            .then((res) => res.json())
            .then(({ status, data }) => {
              if (status !== "OK") {
                console.error("error updating table state, err:", data, "status: ", status)
              }
              if (data !== "") {
                localStorage.setItem("DataTables_" + settings.sInstance, JSON.stringify(data))
              } else {
                localStorage.removeItem("DataTables_" + settings.sInstance)
              }
            })
            .catch((err) => {
              console.error("error updating table state, err: ", err)
            })
        },
        stateLoadCallback: function (settings, callback) {
          fetch(`/tables/${settings.sTableId}/state`, {
            method: "GET",
          })
            .then((res) => res.json())
            .then(({ status, data }) => {
              if (status !== "OK") {
                console.error("error loading table state, err:", data, "status: ", status)
              }
              var response = data !== "" ? data : JSON.parse(localStorage.getItem("DataTables_" + settings.sInstance))
              callback(response)
            })
            .catch((err) => {
              console.error("error loading table state, err: ", err)
            })
        },
        preDrawCallback: function () {
          // this does not always work.. not sure how to solve the staying tooltip
          try {
            $("#blocks").find('[data-toggle="tooltip"]').tooltip("dispose")
          } catch (e) {}
        },
        drawCallback: function (settings) {
          formatTimestamps()
          $("#blocks").find('[data-toggle="tooltip"]').tooltip()
          highestID = settings._iRecordsTotal
        },
      })
    })
  </script>
{{ end }}
{{ define "css" }}
  <link rel="stylesheet" type="text/css" href="/css/datatables.min.css" />
  <style>
    table.dataTable tbody td {
      vertical-align: middle;
    }
  </style>
{{ end }}
{{ define "content" }}
  <div class="container mt-2">
    <div class="my-3">
      <div class="d-md-flex py-2 justify-content-md-between">
        <h1 class="h4 mb-1 mb-md-0">
          <span class="ml-1 mr-1"><i class="fas fa-cube mr-2"></i>Blocks<span style="color:grey; font-size: 70%; padding-left: 10px;" id="live-highest-block"></span></span>
        </h1>
        <nav class="d-flex flex-wrap-reverse flex-md-nowrap justify-content-center align-items-center" aria-label="breadcrumb">
          <ol style="white-space: nowrap;padding:0; background-color:transparent;" class="breadcrumb font-size-1 flex-nowrap mb-0" style="padding:0; background-color:transparent;">
            <li class="breadcrumb-item"><a href="/" title="Home">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">Blocks</li>
          </ol>
        </nav>
      </div>
    </div>
    <div id="r-banner" info="{{ $.Meta.Templates }}"></div>
    <div class="card">
      <div class="card-body px-0 py-3">
        <div class="table-responsive px-0 py-1">
          <table class="table" id="blocks">
            <thead>
              <tr>
                <th>Epoch</th>
                <th>Slot</th>
                <th>Block</th>
                <th>Status</th>
                <th><span data-toggle="tooltip" data-placement="top" title="Miner / Fee Recipient">Recipient</span></th>
                <th>Proposer</th>
                <th><span data-toggle="tooltip" data-placement="top" title="Transactions">Txn</span></th>
                <th>Gas Used</th>
                <th>Gas Limit</th>
                <th>Base Fee</th>
                <th>Reward</th>
                <th>Burned Fees</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
{{ end }}
